package com.wshare.websocket;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/ws/chatroom")
public class ChatroomWebSocket {
	
	private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());
	
	@OnMessage
	public void handleOnMsg(String msg,Session session) throws IOException{
		synchronized (clients) {
			for(Session client:clients){
				client.getBasicRemote().sendText(msg);
			}
		}
	}
	
	@OnOpen
	public void handleOnOpen(Session session){
		clients.add(session);
	}
	
	@OnClose
	public void handleOnClose(Session session){
		clients.remove(session);
	}
}
